package com.qian.ddj.web.controller;


import com.qian.api.ddj.model.*;
import com.qian.api.ddj.service.IDaiFuOrderService;
import com.qian.api.ddj.service.IDfBusinessService;
import com.qian.api.ddj.service.IUserService;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.web.system.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/ddj/daifu")
public class DaifuOrderController {
    @Autowired
    private IDaiFuOrderService daiFuOrderService;
    @Autowired
    private IUserService userService;

    @GetMapping("/all")
    public PageResp<DaiFuOrder> findAll(PageReq pageReq, DfQueryModel model){
        return daiFuOrderService.findAll(model,pageReq);
    }

    @GetMapping("/user")
    public PageResp<DaiFuOrder> user(PageReq pageReq, DfQueryModel model){
        model.setUserId(SecurityUtils.getUserId());
        User user = userService.findById(SecurityUtils.getUserId());
        model.setDfBusinessId(user.getDfBusinessId());
        return daiFuOrderService.findAll(model,pageReq);
    }

    @PostMapping("/save")
    public void save(DaiFuOrder daiFuOrder){
        daiFuOrderService.save(daiFuOrder);
    }

    @PostMapping("/send")
    public void send(DaiFuOrder daiFuOrder){
        daiFuOrderService.send(daiFuOrder);
    }

    @PostMapping("/unAllow")
    public void unAllow(DaiFuOrder daiFuOrder){
        daiFuOrder.setStatus(StatusDict.FAIL);
        daiFuOrder.setFinishDate(new Date());
        daiFuOrder=daiFuOrderService.save(daiFuOrder);
        userService.unLockMoney(daiFuOrder.getUserId(),daiFuOrder.getRealAmount());
    }

    @PostMapping("/userSave")
    public void userSave(WithdrawModel model){
        String outOrderNo = UUID.randomUUID().toString().replaceAll("-","");
        User user = userService.findById(SecurityUtils.getUserId());
        if (model.getAmount().doubleValue()>user.getBalance().doubleValue()){
            throw new BaseException("用户余额不足");
        }else {
            model.setUserId(user.getUsername());
            model.setOutOrderNo(outOrderNo);
            model.setPhone(user.getPhone());
            daiFuOrderService.submit(model);
        }
    }
}
